package com.demo.thread;

/**
 * 怎么停止线程
 */
public class HowToStopThreadQuestion {

    private void test()throws InterruptedException{
        Action action = new Action();
        Thread t1 = new Thread(action,"t1");
        action.setStoped(true);
        t1.start();
        t1.join();

        Thread t2 = new Thread(()->{
            //isInterrupted 判断操作的对象时那个，
            if(!Thread.currentThread().isInterrupted()){
                action();
            }
        },"t2");

        t2.start();
        t2.interrupt();//中断线程t2线程

        System.out.println("t2:"+t2.isInterrupted());

        //重要的*************** 及判断又清楚/
        //底层实现是调用线程是否中断了，如果是中断的，就清空状态，并且返回当前状态。
        //不是中断的，就返回false
        System.out.println("main 线程是否中断了:"+t2.interrupted());//false
        System.out.println("main 线程是否中断了2:"+t2.interrupted());//false
        //t2.interrupted();//判断调用的当前线程是否中断了
    }

    public static void main(String[] args) throws InterruptedException {
        HowToStopThreadQuestion a = new HowToStopThreadQuestion();
        a.test();
    }

    private static void action(){

        System.out.printf("线程：%s 在运行",Thread.currentThread().getName());
    }

    private static class Action implements  Runnable{

        //线程安全问题，确保可见性(Happens-before)
        private volatile  boolean stoped = false;

        @Override
        public void run() {

            if(!stoped){
                action();
            }
        }

        public void setStoped(boolean stoped) {
            this.stoped = stoped;
        }

    }

}
